/**
 * @file util.h
 * @brief Utility functions
 * @author Scott Moyers
 * @date 2009
 */

#ifndef MY_UTIL_H
#define MY_UTIL_H

#include <stdlib.h>

/**
 * Get a bit from an integer
 * @param i input value
 * @param n the bit to get
 * @return the bits value (1 or 0)
 */
#define GET_BIT(n, i) (((i) >> (n)) & 0x01)

/**
 * Set a bit in an integer
 * @param i input integer
 * @param n the bit to set
 */
#define SET_BIT(n, i) ((i) |= 1 << (n))

/**
 * Macro for log to base 2
 * @param x the number to log
 */
#define LOG2(x) (log(x)/log(2))

/**
 * Converts a binary number into its equivalent
 * gray code number
 * @param x input binary number
 * @return the x'th graycode number
 */
#define bin_to_gray(x) ((x) ^ ((x) >> 1))

/**
 * Counts the number of set bits in an integer
 * @param i an integer to count the number of ones in
 * @return the number of set bits in i
 */
int number_of_set_bits(int i);

/**
 * Prints the integer i into the given char buffer
 * as a binary string
 * @param buf char buffer
 * @param val integer to print as binary
 * @param bits number of bits to convert
 */
void to_binary(char *buf, int val, int bits);

/**
 * Swaps 2 variables. upon return a will be in
 * b and b will be in a.
 * @param a int pointer
 * @param b int pointer
 */
void swap(int *a, int *b);

/**
 * Adds up all the number from 1 to n
 * @param n the number you wish to find the sum of numbers for
 * @return the sum of all the numbers from 1 to n
 */
unsigned int sum_of_1_n(unsigned int n);

/**
 * Safe version of malloc. Exits if there's no memory available.
 * @param s size of the requsted data area in bytes
 * @return a pointer to a memory location containing s bytes
 */
void *smalloc(size_t s);

/**
 * Safe version of calloc. Exits if there's no memory available.
 * @param e number of elements of size s
 * @param s size of the requsted data area in bytes
 * @return a pointer to a zero'd memory location containing s*e bytes
 */
void *scalloc(size_t e, size_t s);

#endif


